<template>
  <view>
    <view>
      预约情况：{{count}}/{{professorParams.serviceLimit}}
    </view>
    <view>
      <Date @change="changeDate"></Date>
    </view>
    <view class="order-container">
      <button @click="cancelOrder" :disabled='!isOrder'>取消预约</button>
      <button type="primary" @click="setOrder" :disabled='count>=professorParams.serviceLimit||isOrder'>{{!isOrder?'预 约':'已预约'}}</button>
    </view>
  </view>
</template>

<script>
import { getAppointments, myOrder, setOrder, delOrder } from '../../utils/http';
import Date from '../../components/date/date.vue'
export default {
  components: {
    Date
  },
  data () {
    return {
      professorParams: {},
      appointmentsList: [],
      myOrderList: [],
      order: {},
      count: 0
    };
  },
  created () {
    this.$route.query.professorId = Number(this.$route.query.professorId)
    this.$route.query.userId = Number(this.$route.query.userId)
    console.log("🚀 ~ file: appointments.vue:35 ~ created ~ this.$route.query:", this.$route.query)
    this.professorParams = this.$route.query
    this.getAppointment()
    this.getMyOrder()
  },
  computed: {
    isOrder () {
      const { date, timeId } = this.professorParams;
      let hasOrder = false;
      let order = {};
      for (const item of this.myOrderList) {
        if (item.date === date && item.timeId === timeId) {
          hasOrder = true;
          order = item;
          break;
        }
      }
      this.order = hasOrder ? order : {};
      console.log("🚀 ~ file: appointments.vue:44 ~ isOrder ~ this.order:", this.order);
      return hasOrder;
    }
  },
  methods: {
    changeDate (e) {
      this.professorParams = { ...this.professorParams, ...e }
    },
    async getAppointment () {
      const { data } = await getAppointments(this.professorParams.professorId)
      this.appointmentsList = data
      this.count = 0
      data.forEach(element => {
        this.count = this.count + element.count
      });
      this.getMyOrder()
      console.log("🚀 ~ file: appointments.vue:21 ~ getAppointment ~ data:", data)
    },
    async getMyOrder () {
      const { data } = await myOrder(this.professorParams.userId)
      this.myOrderList = data
      console.log("🚀 ~ file: appointments.vue:42 ~ getMyOrder ~ data:", data)
    },
    async setOrder () {
      const { data } = await setOrder(this.professorParams)
      this.getAppointment()
      console.log("🚀 ~ file: appointments.vue:42 ~ getMyOrder ~ data:", data)
    },
    async cancelOrder () {
      const { data } = await delOrder(this.order.id)
      this.getAppointment()
    }
  }
}
</script>

<style lang="scss">
.order-container {
  display: flex;
}
</style>
